using System.Collections.Generic;
using System.Windows;
using System.Windows.Media;

namespace WPFUtilities
{
    public class BreadthFirstVisualTreeIterator : VisualTreeIterator
    {
        public override IEnumerable<DependencyObject> GetNodes(DependencyObject root)
        {
            Queue<DependencyObject> queue = new Queue<DependencyObject>();
            queue.Enqueue(root);
            while (queue.Count > 0)
            {
                DependencyObject child = queue.Dequeue();
                yield return child;
                EnqueueChildren(queue, child);
            }
        }

        private static void EnqueueChildren(Queue<DependencyObject> queue, DependencyObject root)
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++)
            {
                queue.Enqueue(VisualTreeHelper.GetChild(root, i));
            }
        }
    }
}
